<template>
  <div>
    <!-- 搜索区域 -->
    <div style="margin-bottom: 20px">
      <el-input v-model="data.clubName" placeholder="请输入社团名称" style="width: 200px" clearable></el-input>
      <el-input v-model="data.studentName" placeholder="请输入学生姓名" style="width: 200px; margin-left: 10px" clearable></el-input>
      <el-button type="primary" style="margin-left: 10px" @click="load">查询</el-button>
      <!-- 社长不应该新增成员，新增成员应该是学生报名后由社长审批 -->
      <!-- <el-button type="primary" style="margin-left: 10px" @click="handleAdd">新增</el-button> -->
      <el-button type="danger" style="margin-left: 10px" :disabled="!data.ids.length" @click="delBatch">批量删除</el-button>
      <el-button type="primary" style="margin-left: 10px" @click="showPendingApprovalList">待审批列表</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column prop="id" label="ID" width="80" /> -->
      <el-table-column prop="clubName" label="社团名称" />
      <el-table-column prop="studentName" label="学生姓名" />
      <el-table-column prop="presidentName" label="社长姓名" />
      <el-table-column prop="role" label="成员角色" />  <!-- 新增：显示成员角色 -->
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <!-- 社长可以删除成员 -->
          <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div style="margin-top: 20px">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 表单对话框 -->
    <el-dialog v-model="data.formVisible" :title="data.form.id ? '编辑' : '新增'" width="500px">
      <el-form :model="data.form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="成员角色" prop="role">
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审批报名对话框 -->
    <el-dialog
        v-model="applicationDialogVisible"
        title="报名审批"
        width="60%"
    >
      <el-table :data="currentClubApplicationList" stripe border>
        <el-table-column prop="studentName" label="学生姓名" width="200" align="center"  />
        <el-table-column prop="applyTime" label="申请时间" show-overflow-tooltip align="center"  />
        <el-table-column prop="status" label="审批状态" width="300" align="center" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
                type="success"
                size="small"
                @click="handleApprove(scope.row)"
                :disabled="scope.row.status !== '待审核' || isProcessing"
            >通过</el-button>
            <el-button
                type="danger"
                size="small"
                @click="handleReject(scope.row)"
                :disabled="scope.row.status !== '待审核' || isProcessing"
            >拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {dayjs, ElMessage, ElMessageBox} from 'element-plus'
import request from '@/utils/request'

const formRef = ref()
// 从 localStorage 获取当前用户信息
const user = JSON.parse(localStorage.getItem('xm-pro-user'))
const loading = ref(false)

const data = reactive({
  clubName: null,
  studentName: null,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {},
  ids: [],
  // 以下字段在社长端不需要加载或编辑
  // clubs: [],
  // students: [],
  // presidents: []
})
const isProcessing = ref(false)

// 表单验证规则 (只验证社长可以编辑的字段)
const rules = {
  role: [
     { required: true, message: '请输入成员角色', trigger: 'blur' }
   ]
}

const applicationDialogVisible = ref(false)
const currentClubApplicationList = ref([]);

// 加载数据
const load = () => {
  // 使用社长ID和搜索条件查询成员
  console.log('当前登录用户ID (presidentId):', user.id);
  console.log('发送给后端的params:', {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    clubName: data.clubName,
    studentName: data.studentName,
    presidentId: user.id // 将当前社长ID传递给后端
  });
  request.get('/clubmember/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      clubName: data.clubName,
      studentName: data.studentName,
      presidentId: user.id // 将当前社长ID传递给后端
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data.list
      data.total = res.data.total
    } else {
      ElMessage.error(res.msg || '加载数据失败')
    }
  }).catch(err => {
    console.error('加载数据失败:', err)
    ElMessage.error('加载数据失败')
  })
}

// 编辑
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  // 只保留可以编辑的字段
  data.form = {
    id: data.form.id,
    role: data.form.role
  }
  data.formVisible = true
}

// 保存
const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 社长端只有编辑功能，没有新增
      // if (data.form.id) {
         update()
      // } else {
      //   add()
      // }
    }
  })
}

// 更新请求
const update = () => {
  request.put('/clubmember/updateById', data.form).then(res => {
    if (res.code === '200') {
      data.formVisible = false
      ElMessage.success('更新成功')
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 删除
const del = (id) => {
  ElMessageBox.confirm('确认删除该社团成员吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.delete('/clubmember/deleteById/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    }).catch(err => {
      console.error('删除失败:', err)
      ElMessage.error('删除失败')
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除
const handleSelectionChange = (rows) => {
  data.ids = rows.map(item => item.id)
}

const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning('请选择要批量删除的数据')
    return
  }
  ElMessageBox.confirm('确认批量删除这些社团成员吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.delete('/clubmember/deleteBatch', { data: data.ids }).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    }).catch(err => {
      console.error('批量删除失败:', err)
      ElMessage.error('批量删除失败')
    })
  }).catch(() => {
    ElMessage.info('已取消批量删除')
  })
}

const showPendingApprovalList = () => {
  loading.value = true
  //获取社团的申请数据，放入响应式对象，对象数据绑定在弹框中,根据响应式对象来控制他是否显示
    const res = request.get('/club/application/list', {
      params: {
        clubId: user.clubId,
        pageNum: 1,
        pageSize: 10
      }
    }).then(res => {
      if (res.code === '200') {
        // 处理列表中的 applyTime 字段
        const formattedList = res.data.list.map(item => ({
          ...item,
          applyTime: dayjs(item.applyTime).format('YYYY年MM月DD日')
        }));
        currentClubApplicationList.value = formattedList;
      } else {
        ElMessage.error(res.msg || '查询失败')
      }
    }).catch(err => {
      console.error('查询失败:', err)
      ElMessage.error('查询失败')
    }).finally(() => {
      loading.value = false
      applicationDialogVisible.value = true
    })
}

const handleApprove = async (row) => {
  //修改社团申请表的状态
  try {
    const res = await request.post('/club/application/approve', {
      id: row.id,
      status: '已通过'
    })
    if (res.code === '200') {
      ElMessage.success('审批成功')
      // 更新当前报名列表的状态
      row.status = '已通过'
      isProcessing.value = true
    } else {
      ElMessage.error(res.msg || '审批失败')
    }
  } catch (err) {
    ElMessage.error('审批失败')
    console.error(err)
  }
}

const handleReject = async (row) => {
  try {
    const res = await request.post('/club/application/reject', {
      id: row.id,
      status: '已拒绝'

    })
    if (res.code === '200') {
      ElMessage.success('拒绝成功')
      // 更新当前报名列表的状态
      row.status = '已拒绝'
      isProcessing.value = true

    } else {
      ElMessage.error(res.msg || '拒绝失败')
    }
  } catch (err) {
    ElMessage.error('拒绝失败')
    console.error(err)
  }
}

// 分页
const handleSizeChange = (pageSize) => {
  data.pageSize = pageSize
  load()
}

const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum
  load()
}

onMounted(() => {
  load()
  // 社长端不需要加载所有社团、学生、社长列表，注释或移除这些调用
  // loadClubs()
  // loadStudents()
  // loadPresidents()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 